# -*- coding: utf-8 -*-

'''
Created on May 16, 2011

@author: peterd
'''

import django.utils.simplejson as json, sys
import urllib,urllib2

from django.core.exceptions import ObjectDoesNotExist

from web.service.HttpReader import HttpReader
from mhd.models import MHD_Stop_Type, MHD_Link_Type, MHD_Link, MHD_Stop, MHD_Link_Stop, MHD_Link_Direction
from mhd.parser import MHD_LinkStopListParser

#29536
#http://mapa.zoznam.sk/ws.php?obj_id=30829&_=1305634369016
#{"objects":[{"cat_id":"374","name":"\u017dST Nov\u00e9 Mesto","x":"48.171842","description":"Linky:1","y":"17.144857","cat_name":"Elektri\u010dkov\u00e1 zast\u00e1vka","url":"http:\/\/imhd.zoznam.sk\/","address":"","id":"7699","cat_kw":"MHD;Bratislava;Slovakia;zast\u00e1vka","altid":"ID_30829"}]}


zstops = {}
json_data=open('ba_stops_resp')
for stop in json.load(json_data)['objects']:
    zstops[stop['altid'].replace('ID_', '')] = {'lat': stop['x'], 'lng': stop['y'], 'type': stop['cat_name']}

url = 'http://www.imhd.zoznam.sk/ba/index.php'

class MHD_Link_Type_NotPopulated:
    pass


mhd_nodes = []
mhd_nodes.append({'links': 'provisioning/trams.txt', 'link_type': u'Električka', 'stop_type': u'Zastávka električky'})
mhd_nodes.append({'links': 'provisioning/troleys.txt', 'link_type': u'Trolejbus', 'stop_type': u'Zastávka trolejbusu'})
mhd_nodes.append({'links': 'provisioning/buses.txt', 'link_type': u'Autobus', 'stop_type': u'Zastávka autobusu (denná linka)'})
# REVISIT: enable once proves useful
#mhd_nodes.append({'links': 'provisioning/night_buses.txt', 'link_type': u'Nočný autobus', 'stop_type': u'Zastávka autobusu (nočná linka)'})
#mhd_nodes.append({'links': 'provisioning/region_buses.txt', 'link_type': u'Regionálny autobus', 'stop_type': u'Zastávka autobusu (regionálna linka)'})

for mhd_node in mhd_nodes:
    for link in open(mhd_node['links'], 'r'):
        link = link.strip()
                                                
        print "loading link %s" % link
        
        parameters = {'x':10, 'y':12, 'hladaj':link, 'w':'212b2e292cef2f302523ea'}    
        data = urllib.urlencode(parameters)
        request = urllib2.Request(url, data)
        response = urllib2.urlopen(request)
        
        mhd_link_stop_list_parser = MHD_LinkStopListParser()
        routes = mhd_link_stop_list_parser.parse(response.read().decode('cp1250'))
        
        mhd_link_type = MHD_Link_Type.objects.get(name = mhd_node['link_type'])
        if not mhd_link_type:
            raise MHD_Link_Type_NotPopulated
        
        mhd_link = None
        try:
            mhd_link = MHD_Link.objects.get(name = link, link_type = mhd_link_type)
        except ObjectDoesNotExist:
            mhd_link = MHD_Link(name = link, link_type = mhd_link_type)
            mhd_link.save()
        
        mhd_stop = None
        
        for route in routes:
            try:
                direction = route['direction']
            except IndexError:
                print "no route for link %s" % link 
                continue
            
            if not direction:
                continue
            
            mhd_link_direction = None
            try:
                mhd_link_direction = MHD_Link_Direction.objects.get(link = mhd_link, direction = direction)
            except ObjectDoesNotExist:
                mhd_link_direction = MHD_Link_Direction(link = mhd_link, direction = direction)
                mhd_link_direction.save()
            
            stop_num = 1
            for stop in route['stops']:
                if zstops.has_key(stop['id']):
                    zstop = zstops[stop['id']]
                    
                    mhd_stop_type = None
                    try:
                        mhd_stop_type = MHD_Stop_Type.objects.get(name = zstop['type'])
                    except ObjectDoesNotExist:
                        mhd_stop_type = MHD_Stop_Type(name = zstop['type'])
                        mhd_stop_type.save()
                    
                    try:               
                        mhd_stop = MHD_Stop.objects.get(zoid = int(stop['id']))
                    except ObjectDoesNotExist:
                        mhd_stop = MHD_Stop(name = stop['name'], zoid = stop['id'], lat = zstop['lat'], lng = zstop['lng'], stop_type = mhd_stop_type)
                        mhd_stop.save()                        
                                               
                else:
                    mhd_stop_type = None
                    try:
                        mhd_stop_type = MHD_Stop_Type.objects.get(name = mhd_node['stop_type'])
                    except ObjectDoesNotExist:
                        mhd_stop_type = MHD_Stop_Type(name = mhd_node['stop_type'])
                        mhd_stop_type.save()
                        
                    if stop['id'] == 0:
                        print "stop %s not marked in zoznam" % stop['name'].encode('cp1250')
                        hint = '%d. stop of link %s, direction %s' % (stop_num, link, direction)
                        try:
                            mhd_stop = MHD_Stop.objects.get(name = stop['name'], zoid = stop['id'], lat = 0.0, lng = 0.0, stop_type = mhd_stop_type, 
                                            hint = hint)                            
                        except ObjectDoesNotExist:
                            mhd_stop = MHD_Stop(name = stop['name'], zoid = stop['id'], lat = 0.0, lng = 0.0, stop_type = mhd_stop_type, 
                                            hint = '%d. stop of link %s, direction %s' % (stop_num, link, direction))
                            mhd_stop.save()                                                                        
                    else:        
                        httpReader = HttpReader()
                        data = httpReader.read(url = 'http://mapa.zoznam.sk/ws.php?obj_id=%s&_=1305634369016' % (stop['id']))
            
                        if data == 'null':
                            print "stop %s not marked in zoznam" % stop['name'].encode('cp1250')
            
                            try:               
                                mhd_stop = MHD_Stop.objects.get(zoid = int(stop['id']))
                            except ObjectDoesNotExist:
                                mhd_stop = MHD_Stop(name = stop['name'], zoid = stop['id'], lat = 0.0, lng = 0.0, stop_type = mhd_stop_type, 
                                                    hint = '%d. stop of link %s, direction %s' % (stop_num, link, direction))
                                mhd_stop.save()                        
                        else:
                            try:               
                                mhd_stop = MHD_Stop.objects.get(zoid = int(stop['id']))
                            except ObjectDoesNotExist:
                                slat = data['objects'][0]['x']
                                slng = data['objects'][0]['y']
                                mhd_stop = MHD_Stop(name = stop['name'], zoid = stop['id'], lat = slat, lng = slng, stop_type = mhd_stop_type) 
                                mhd_stop.save()                        
                    
                mhd_link_stop = None
                try:        
                    mhd_link_stop = MHD_Link_Stop.objects.get(link = mhd_link, stop = mhd_stop, stop_number = stop_num, direction = mhd_link_direction)
                except ObjectDoesNotExist:
                    mhd_link_stop = MHD_Link_Stop(link = mhd_link, stop = mhd_stop, stop_number = stop_num, direction = mhd_link_direction)
                    mhd_link_stop.save()
                    
                if stop_num == 1:
                    mhd_link_direction.timetable_url = stop['timetable_url']
                    mhd_link_direction.save()
        
                stop_num = stop_num + 1        